const http = require('http');

// 测试创建游戏API
function testCreateGame() {
  const postData = JSON.stringify({
    Name: 'Test Game',
    GridSize: 10,
    MaxPlayers: 4
  });

  const options = {
    hostname: 'localhost',
    port: 5258,
    path: '/api/Game',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(postData)
    }
  };

  const req = http.request(options, (res) => {
    console.log(`创建游戏API - 状态码: ${res.statusCode}`);
    
    let data = '';
    res.on('data', (chunk) => {
      data += chunk;
    });

    res.on('end', () => {
      console.log('创建游戏API - 响应:', data);
      
      // 如果创建成功，获取游戏ID并测试其他API
      if (res.statusCode === 201) {
        try {
          const gameId = data.trim();
          console.log(`获取到的游戏ID: ${gameId}`);
          
          // 等待1秒后测试获取游戏详情
          setTimeout(() => {
            testGetGame(gameId);
          }, 1000);
          
          // 等待2秒后测试获取所有游戏
          setTimeout(() => {
            testGetActiveGames();
          }, 2000);
        } catch (e) {
          console.error('解析游戏ID失败:', e);
        }
      }
    });
  });

  req.on('error', (e) => {
    console.error(`创建游戏API - 错误: ${e.message}`);
  });

  // 写入数据
  req.write(postData);
  req.end();
}

// 测试获取游戏详情API
function testGetGame(gameId) {
  const options = {
    hostname: 'localhost',
    port: 5258,
    path: `/api/Game/${gameId}`,
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const req = http.request(options, (res) => {
    console.log(`\n获取游戏详情API - 状态码: ${res.statusCode}`);
    
    let data = '';
    res.on('data', (chunk) => {
      data += chunk;
    });

    res.on('end', () => {
      console.log('获取游戏详情API - 响应:', data);
    });
  });

  req.on('error', (e) => {
    console.error(`获取游戏详情API - 错误: ${e.message}`);
  });

  req.end();
}

// 测试获取所有活跃游戏API
function testGetActiveGames() {
  const options = {
    hostname: 'localhost',
    port: 5258,
    path: '/api/Game',
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const req = http.request(options, (res) => {
    console.log(`\n获取所有活跃游戏API - 状态码: ${res.statusCode}`);
    
    let data = '';
    res.on('data', (chunk) => {
      data += chunk;
    });

    res.on('end', () => {
      console.log('获取所有活跃游戏API - 响应:', data);
    });
  });

  req.on('error', (e) => {
    console.error(`获取所有活跃游戏API - 错误: ${e.message}`);
  });

  req.end();
}

// 开始测试
console.log('开始测试后端API...');
testCreateGame();